/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.xui_lib.component.imageview.edit;

import ohos.agp.utils.Color;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;

/**
 * 图片工具类
 *
 * @author xuexiang
 * @since 2019-10-28 9:52
 */
class BitmapUtil {
    /**
     * Remove transparency in edited bitmap
     *
     * @param source edited image
     * @return bitmap without any transparency
     */
    static PixelMap removeTransparency(PixelMap source) {
        Size sourceSize = source.getImageInfo().size;
        int firstX = 0, firstY = 0;
        int lastX = sourceSize.width;
        int lastY = sourceSize.height;
        int[] pixels = new int[sourceSize.width * sourceSize.height];
        Rect region = new Rect(0, 0, sourceSize.width, sourceSize.height);
        source.readPixels(pixels, 0, sourceSize.width, region);
        loop:
        for (int x = 0; x < sourceSize.width; x++) {
            for (int y = 0; y < sourceSize.height; y++) {
                if (pixels[x + (y * sourceSize.width)] != Color.TRANSPARENT.getValue()) {
                    firstX = x;
                    break loop;
                }
            }
        }
        loop:
        for (int y = 0; y < sourceSize.height; y++) {
            for (int x = firstX; x < sourceSize.height; x++) {
                if (pixels[x + (y * sourceSize.width)] != Color.TRANSPARENT.getValue()) {
                    firstY = y;
                    break loop;
                }
            }
        }
        loop:
        for (int x = sourceSize.width - 1; x >= firstX; x--) {
            for (int y = sourceSize.height - 1; y >= firstY; y--) {
                if (pixels[x + (y * sourceSize.width)] != Color.TRANSPARENT.getValue()) {
                    lastX = x;
                    break loop;
                }
            }
        }
        loop:
        for (int y = sourceSize.height - 1; y >= firstY; y--) {
            for (int x = sourceSize.width - 1; x >= firstX; x--) {
                if (pixels[x + (y * sourceSize.width)] != Color.TRANSPARENT.getValue()) {
                    lastY = y;
                    break loop;
                }
            }
        }

        return PixelMap.create(source, new Rect(firstX, firstY, lastX - firstX, lastY - firstY), null);
    }
}
